package com.az.securitycommon.filter;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.az.miaoapi.dto.UserDto;
import com.az.miaoapi.exception.BaseException;
import com.az.miaoapi.response.ResponseCode;
import feign.RequestTemplate;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

@RequiredArgsConstructor
public class SecurityFilter extends OncePerRequestFilter {

    private final RequestTemplate requestTemplate;

    // 根据角色返回权限
    private Collection<GrantedAuthority> empower(String role) {
        Collection<String> powers = new ArrayList<>();
        switch (role) {
            case "guest":
                powers.add("guest");
                break;
            case "student":
                powers.add("student");
                powers.add("loginUser");
                break;
            case "teacher":
                powers.add("teacher");
                powers.add("loginUser");
                break;
            case "admin":
                powers.add("admin");
                powers.add("loginUser");
                break;
            default:
                throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
        return AuthorityUtils.createAuthorityList(powers);
    }


    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request,
                                    @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("token");
        if (token == null || !JWTUtil.verify(token, "miao".getBytes())) {
            throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
        UserDto authorization;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            JWTValidator validator = JWTValidator.of(jwt);
            validator.validateDate();
            authorization = new UserDto(
                    Long.parseLong(jwt.getPayload("userId").toString()),
                    jwt.getPayload("role").toString());
        } catch (RuntimeException e) {
            throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                authorization.getUserId(),
                null,
                empower(authorization.getRole()));
        //设置用户信息
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        requestTemplate.header("token", token);
        filterChain.doFilter(request, response);
    }
}
